package com.jiang.jetpackdemo.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.utils.CacheUtil
import com.jiang.jetpackdemo.viewModel.SettingViewModel
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class SettingActivity : AppCompatActivity() {
    lateinit var viewModel: SettingViewModel
    lateinit var cacheUtil: CacheUtil
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)

        initViewModel()
        initListener()
        cacheUtil = CacheUtil(applicationContext)
        refreshCacheSize()


    }

    private fun refreshCacheSize() {
        viewModel.imageCacheSize.value = cacheUtil.getImageCacheSize()
        GlobalScope.launch(Dispatchers.Main) {
            viewModel.requestCacheSize.value = cacheUtil.getVideoRequestCacheSize()
        }
    }

    private fun initListener() {
        btn_clear.setOnClickListener {
            GlobalScope.launch(Dispatchers.Main) {
                cacheUtil.clearImageCacheSize()
                refreshCacheSize()
                Toast.makeText(this@SettingActivity, "清理完成", Toast.LENGTH_SHORT).show()
            }

        }
        btn_clear_request.setOnClickListener {
            cacheUtil.clearVideoRequestCache()
            refreshCacheSize()
            Toast.makeText(this, "清理完成", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initViewModel() {
        viewModel = ViewModelProvider(this).get(SettingViewModel::class.java)
        viewModel.imageCacheSize.observe(
            this,
            Observer { t ->
                btn_clear.text = "${resources.getString(R.string.clear_image_cache)} (${t} M)"
            })
        viewModel.requestCacheSize.observe(
            this,
            Observer { t ->
                btn_clear_request.text =
                    "${resources.getString(R.string.clearRequestCache)} (${t} k)"
            })
    }

}
